13-1 c}C堨

每一個結構陣列(Structure Array)可以包含很多個元素,每一個元素可以看成是一筆資料。因此每個元素可以包含數個欄位(Fields),而每個欄位可包含各個不同型態的資料。例如一個包含學生個人資料的結構陣列,可能含有的欄位是 name(學生姓名)、id(學號)、scores(小考成績)等。要建立此種結構,可在指令列直接輸入個欄位的值,如下:

Example 1: 13-結構陣列/struct01.mclear student % 清除 student 變數 student.name = '洪鵬翔'; % 加入 name 欄位 student.id = 'mr871912'; % 加入 id 欄位 student.scores = [58, 75, 62]; % 加入 scores 欄位 student % 秀出結果 student = name: '洪鵬翔' id: 'mr871912' scores: [58 75 62]

此時 student 即代表一個結構陣列的第一個元素,或是第一筆資料。欲加入第二筆資料(或是第二個元素),可輸入如下:

Example 2: 13-結構陣列/struct02.mclear student % 清除 student 變數 student.name = '洪鵬翔'; % 加入 name 欄位 student.id = 'mr871912'; % 加入 id 欄位 student.scores = [58, 75, 62]; % 加入 scores 欄位 % 以下是新加入的第二筆資料 student(2).name = '邱中人'; student(2).id = 'mr872510'; student(2).scores = [25, 36, 92]; student % 秀出結果 student = 1x2 <a href="matlab:helpPopup struct" style="font-weight:bold">struct</a> array with fields: name id scores

此時 student 即代表一個 1×2 的結構陣列。由於此結構陣列已漸趨複雜,MATLAB 並不將所有欄位值印出。欲顯示某元素的特定欄位值,可輸入明確的敘述,例如 student(2).scores 等。

上述的 student 結構陣列可圖示如下:

變數nameidscores
student(1)'洪鵬翔''mr871912'[58,75,62]
student(2)'邱中人''mr872510'[25,36,92]

另一個建立結構陣列的方法,則是使用 struct 指令,其格式如下:

structureArray = struct(field1, value1, field2, value2,….)

其中 field1、field2、…是欄位名稱,value1、value2、…則是欄位所包含的資料。如果 value1、value2、…為異質陣列(Cell Arrays,詳見第上一章),則 MATLAB 會依序將異質陣列的每個元素設定為每一個結構中相對應的欄位值,如下:

Example 3: 13-結構陣列/struct03.mstudent = struct('name', {'張庭碩', '張庭安'}, 'scores', {[50 60], [60 70]}); student(1) % 顯示 student(1) student(2) % 顯示 student(2) ans = name: '張庭碩' scores: [50 60] ans = name: '張庭安' scores: [60 70]

在上述使用法中,{'張庭碩', '張庭安'} 和 {[50 60], [60 70]} 都是異質陣列,因此他們的每個元素會被依次設定到每個結構之中。但是如果其中有一個異值陣列的長度是1,那麼 MATLAB 會進行「純量展開」(Scalar Expansion)來自動補足,範例如下:

Example 4: 13-結構陣列/struct04.mstudent = struct('name', '張庭安', 'scores', {[50 60], [90 100]}); student(1) % 顯示 student(1) student(2) % 顯示 student(2) ans = name: '張庭安' scores: [50 60] ans = name: '張庭安' scores: [90 100]

在上述範例中,「張庭安」可視為異質陣列的一個元素,因此在設定至 student 結構陣列時,MATLAB 會進行純量展開,將「張庭安」分別設定到 student 的兩個元素的 name 欄位值。

結構陣列可以是巢狀式(Nested)的,也就是說,結構陣列的欄位可是另一個結構陣列,我們可以藉此產生複雜的資料結構。舉例來說,若要加入第二位學生所修的兩門課程和學分,可見下列範例:

Example 5: 13-結構陣列/struct05.mstudent = struct('name', {'張庭碩', '張庭安'}, 'scores', {[50 60], [60 70]}); student(2).course(1).title = 'Web Programming'; student(2).course(1).credits = 2; student(2).course(2).title = 'Numerical Method'; student(2).course(2).credits = 3; student(2).course ans = 1x2 <a href="matlab:helpPopup struct" style="font-weight:bold">struct</a> array with fields: title credits

Hint
在上例中,student(1).course 會自動被預設成空矩陣。

我們亦可一筆一筆地建立 student 結構陣列,如下:

Example 6: 13-結構陣列/buildStruct01.mclear student % 清除 student 變數 student(1) = struct('name', 'Banny', 'scores', [85,80,92,78]); student(2) = struct('name', 'Joey', 'scores', [80,85,90,88]); student(3) = struct('name', 'Betty', 'scores', [88,82,90,80]);

上述的 student 結構陣列,可圖示如下:


MATLAB程式設計:入門篇